package com.swang.framework.core.util;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * @ClassName: OssUtil
 * @Description: Oss工具
 * @author swang@swang.com
 * @date 2017年3月16日 下午9:45:51
 */
@SuppressWarnings("unused")
public class OssUtil {

    private static OSSClient               ossClient;
    private static HashMap<String, String> bucketMap;
    private static String                  ossEndpoint = "http://swang.com/";

    private static Logger                  logger      = Logger.getLogger(OssUtil.class);

    static {
        //暂时这么处理 后期优化
        ossClient = new OSSClient("http://oss.aliyuncs.com/", "TezdrEdw1wzPQcKG", "M0L0giSosrMe4bAakh6v8TaBk9pVvN");
    }

    /**
     * 保存资源文件到阿里云
     * 
     * @param bucketName 库名
     * @param key 文件名
     * @param input
     * @param size
     * @param creator 上传人
     * @param descn 描述
     * @param moduleId 模块类型
     * @param moduleType 用于app上传模块，为IOS，Android 其余可为PC
     * @return key
     */
    public static String save(String bucketName, String key, InputStream input, Long size, String creator, String descn, String moduleId,
                              String moduleType) {
        String attachName = null;
        String changeKey = null;
        int nIndexEnd = key.lastIndexOf('.');// 截取最后一个.的位置
        String extension = key.substring(nIndexEnd);// 获取后缀名
        String uuid = UUIDUtil.createUUID();
        attachName = key.substring(0, nIndexEnd);
        if (!moduleId.equals("Upgrade")) {
            changeKey = moduleId + "_" + uuid + extension;
            key = changeKey;
        } else {
            if (moduleType.equals("Android")) {
                changeKey = key;
            } else {
                changeKey = attachName;
            }
        }
        try {
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(size);
            if (key.endsWith("xml")) {
                objectMeta.setContentType("text/xml");
            } else if (key.endsWith("jpg") || key.endsWith("JPG")) {
                objectMeta.setContentType("image/jpeg");
            } else if (key.endsWith("png") || key.endsWith("PNG")) {
                objectMeta.setContentType("image/png");
            } else if (key.endsWith("jpeg") || key.endsWith("JPEG")) {
                objectMeta.setContentType("image/jpeg");
            } else if (key.endsWith("gif") || key.endsWith("GIF")) {
                objectMeta.setContentType("image/gif");
            } else if (key.endsWith("bmp") || key.endsWith("BMP")) {
                objectMeta.setContentType("image/bmp");
            } else if (key.endsWith("html")) {
                objectMeta.setContentType("text/html");
            }
            ossClient.putObject(bucketName, key, input, objectMeta);
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return changeKey;
    }

    /**
     * 上传用户须知模板到阿里云
     * 
     * @param bucketName
     * @param key
     * @param input
     * @param size
     * @return
     */
    public static String saveNoticeTemplate(String bucketName, String key, InputStream input, Long size, String hosId) {
        String attachName;
        String changeKey = "";
        try {
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(size);

            objectMeta.setContentType("text/html");

            key = hosId + "/" + key + ".html";
            ossClient.putObject(bucketName, key, input, objectMeta);
            //			changeKey = hosId + "/" + key + ".html";
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return key;
    }

    public static boolean saveByType(String bucketName, String key, InputStream input, Long size, String type) {
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(size);
        objectMeta.setContentType(type);
        try {
            ossClient.putObject(bucketName, key, input, objectMeta);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 重载save 云端保存
     * 
     * @Description: TODO
     * @param bucketName
     * @param changeKey
     * @param input
     * @param fileSize
     * @return
     * @Author: hurd
     * @Date: 2015年8月3日 上午9:55:33
     */
    public static boolean save(String bucketName, String changeKey, InputStream input, long fileSize) {
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(fileSize);
        if (changeKey.endsWith("xml")) {
            objectMeta.setContentType("text/xml");
        } else if (changeKey.endsWith("jpg") || changeKey.endsWith("JPG")) {
            objectMeta.setContentType("image/jpeg");
        } else if (changeKey.endsWith("png") || changeKey.endsWith("PNG")) {
            objectMeta.setContentType("image/png");
        } else if (changeKey.endsWith("jpeg") || changeKey.endsWith("JPEG")) {
            objectMeta.setContentType("image/jpeg");
        } else if (changeKey.endsWith("gif") || changeKey.endsWith("GIF")) {
            objectMeta.setContentType("image/gif");
        } else if (changeKey.endsWith("bmp") || changeKey.endsWith("BMP")) {
            objectMeta.setContentType("image/bmp");
        } else if (changeKey.endsWith("html")) {
            objectMeta.setContentType("text/html");
        }
        try {
            ossClient.putObject(bucketName, changeKey, input, objectMeta);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除资源文件
     * 
     * @param bucketName
     * @param key
     * @return
     */
    public static Boolean delete(String bucketName, String key) {
        try {
            ossClient.deleteObject(bucketName, key);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取资源文件url
     * 
     * @param bucketName
     * @param key
     * @return
     */
    public static String getUrl(String bucketName, String key) {
        if (null == key) {
            return null;
        }
        // 统一改成https地址     https://hsknowledgebase.oss-cn-hangzhou.aliyuncs.com
        String http = "http://";
        //		String ossCom = "." + ossEndpoint.replace("http://", "");
        String ossCom = ".swang.com/";
        try {
            key = java.net.URLEncoder.encode(key, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String downloadUrl = http + bucketName + ossCom + key;
        return downloadUrl;
    }

    /**
     * 根据url得到key
     * 
     * @param url
     * @return
     */
    public static String getKey(String url) {
        logger.info("url:" + url);
        String key = null;
        int lastIndex = url.lastIndexOf("/");
        key = url.substring(lastIndex + 1, url.length());
        return key;
    }

    public void setOssClient(OSSClient ossClient) {
        OssUtil.ossClient = ossClient;
    }

    public void setBucketMap(HashMap<String, String> bucketMap) {
        OssUtil.bucketMap = bucketMap;
    }

    public void setOssEndpoint(String ossEndpoint) {
        OssUtil.ossEndpoint = ossEndpoint;
    }

}
